package com.it.travel.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.it.travel.vo.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RequestMapping("upload")
@RestController
@CrossOrigin
public class UploadController {
    @PostMapping("")
    public Result<String> upload(MultipartFile file) throws IOException { // 分类图片上传接口

        String originalFilename = file.getOriginalFilename();// 获取上传的文件名
        int i = originalFilename.lastIndexOf("."); // 查看最后一个出现.的位置
        String houzui = originalFilename.substring(i);  // 截取 这个索引开始也就是.开始的后缀
        UUID uuid = UUID.randomUUID();
        String url = "http://localhost:8888/upload01/" + uuid + houzui;
        String rootFilePath = System.getProperty("user.dir") + "\\src\\main\\resources\\upload01\\" + uuid+houzui; // 上传到这
        System.out.println("rootFilePath = " + rootFilePath);
        File file1 = FileUtil.writeBytes(file.getBytes(), rootFilePath);
        return Result.success(url, "上传成功");
    }
    @PostMapping("/editor")
    public JSON uploadeditor(MultipartFile file) throws IOException { // 分类图片上传接口

        String originalFilename = file.getOriginalFilename();// 获取上传的文件名
        int i = originalFilename.lastIndexOf("."); // 查看最后一个出现.的位置
        String houzui = originalFilename.substring(i);  // 截取 这个索引开始也就是.开始的后缀
        UUID uuid = UUID.randomUUID();
        String url = "http://localhost:8888/upload01/" + uuid + houzui;
        String rootFilePath = System.getProperty("user.dir") + "\\src\\main\\resources\\upload01\\" + uuid+houzui; // 上传到这
        File file1 = FileUtil.writeBytes(file.getBytes(), rootFilePath);
        JSONObject json = new JSONObject();
        json.set("errno", 0);
        JSONArray arr = new JSONArray();
        JSONObject data = new JSONObject();
        arr.add(data);
        data.set("url", url);
        json.set("data", arr);
        return json;
    }
}
